<template>
  <div class="home-container">
    <h1 class="page-title">💕 欢迎回来</h1>

    <!-- 恋爱倒计时卡片 -->
    <div class="love-countdown-card card">
      <div v-if="coupleInfo" class="countdown-content">
        <!-- 左侧头像（自己） -->
        <div class="avatar-frame left-avatar" @click="openAvatarDialog">
          <div class="heart-frame">
            <svg class="heart-svg" viewBox="0 0 200 200">
              <defs>
                <linearGradient id="heartGradient1" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#ff69b4;stop-opacity:1" />
                  <stop offset="100%" style="stop-color:#ff85c0;stop-opacity:1" />
                </linearGradient>
                <filter id="glow">
                  <feGaussianBlur stdDeviation="3" result="coloredBlur"/>
                  <feMerge>
                    <feMergeNode in="coloredBlur"/>
                    <feMergeNode in="SourceGraphic"/>
                  </feMerge>
                </filter>
              </defs>
              <path d="M100,170 C100,170 30,120 30,80 C30,50 50,30 75,30 C85,30 95,35 100,45 C105,35 115,30 125,30 C150,30 170,50 170,80 C170,120 100,170 100,170 Z"
                    fill="url(#heartGradient1)"
                    stroke="#ff1493"
                    stroke-width="3"
                    filter="url(#glow)"
                    class="heart-path"/>
            </svg>
            <div class="avatar-container">
              <el-avatar :size="100" :src="userInfo?.avatar || defaultAvatar" class="couple-avatar pulse">
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="avatar-name">{{ userInfo?.nickname || '我' }}</div>
              <!-- 悬浮提示 -->
              <div class="avatar-hover-tip">
                <el-icon><Camera /></el-icon>
                <span>更换头像</span>
              </div>
            </div>
          </div>
          <div class="love-particles">
            <span class="particle">💕</span>
            <span class="particle">💖</span>
            <span class="particle">✨</span>
          </div>
        </div>

        <!-- 中间倒计时 -->
        <div class="countdown-center">
          <div class="love-icon floating">💑</div>
          <div class="countdown-text">
            <h2>在一起的第</h2>
            <div class="countdown-days">{{ loveDays }}</div>
            <p>天</p>
          </div>
          <div class="love-message">{{ loveMessage }}</div>
        </div>

        <!-- 右侧头像（对方） -->
        <div class="avatar-frame right-avatar" @click="viewPartnerBills">
          <div class="heart-frame">
            <svg class="heart-svg" viewBox="0 0 200 200">
              <defs>
                <linearGradient id="heartGradient2" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" style="stop-color:#ff1493;stop-opacity:1" />
                  <stop offset="100%" style="stop-color:#ff69b4;stop-opacity:1" />
                </linearGradient>
              </defs>
              <path d="M100,170 C100,170 30,120 30,80 C30,50 50,30 75,30 C85,30 95,35 100,45 C105,35 115,30 125,30 C150,30 170,50 170,80 C170,120 100,170 100,170 Z"
                    fill="url(#heartGradient2)"
                    stroke="#ff1493"
                    stroke-width="3"
                    filter="url(#glow)"
                    class="heart-path"/>
            </svg>
            <div class="avatar-container">
              <el-avatar :size="100" :src="partnerInfo?.avatar || defaultAvatar" class="couple-avatar pulse">
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="avatar-name">{{ partnerInfo?.nickname || 'TA' }}</div>
              <!-- 悬浮提示 -->
              <div class="avatar-hover-tip">
                <el-icon><View /></el-icon>
                <span>查看账单</span>
              </div>
            </div>
          </div>
          <div class="love-particles">
            <span class="particle">💕</span>
            <span class="particle">💖</span>
            <span class="particle">✨</span>
          </div>
        </div>
      </div>
      <div v-else class="no-couple-content">
        <div class="no-couple-icon">💕</div>
        <h3>还没有情侣关系</h3>
        <p>创建或加入情侣关系，开启甜蜜记账之旅</p>
        <div class="couple-actions">
          <el-button type="primary" @click="goToPage('/create-couple')">创建关系</el-button>
          <el-button @click="goToPage('/join-couple')">加入关系</el-button>
        </div>
      </div>
    </div>

    <!-- 快捷操作区域 -->
    <div class="quick-actions">
      <div class="action-card card" @click="goToPage('/bill/create')">
        <el-icon class="action-icon" color="#ff9a9e"><Wallet /></el-icon>
        <h3>记一笔</h3>
        <p>快速记账</p>
      </div>

      <div class="action-card card" @click="goToPage('/balance')">
        <el-icon class="action-icon" color="#a8dadc"><CreditCard /></el-icon>
        <h3>余额管理</h3>
        <p>微信余额</p>
      </div>

      <div class="action-card card" @click="goToPage('/treasury')">
        <el-icon class="action-icon" color="#fecfef"><Coin /></el-icon>
        <h3>恋爱金库</h3>
        <p>¥ {{ formatAmount(treasuryAmount) }}</p>
      </div>

      <div class="action-card card" @click="goToPage('/bill/list')">
        <el-icon class="action-icon" color="#b8e0d2"><List /></el-icon>
        <h3>账单列表</h3>
        <p>查看所有账单</p>
      </div>

      <div class="action-card card" @click="goToPage('/bill/pending')">
        <el-badge :value="pendingBillsCount" :hidden="pendingBillsCount === 0" type="danger">
          <el-icon class="action-icon" color="#ffd1dc"><Bell /></el-icon>
        </el-badge>
        <h3>待审批</h3>
        <p>{{ pendingBillsCount }} 条待处理</p>
      </div>


    </div>

    <!-- 情感互动展示区 -->
    <div class="emotion-showcase">
      <div class="showcase-grid">
        <!-- 最新日记 -->
        <div class="showcase-card card">
          <div class="showcase-header">
            <h3>📖 最新日记</h3>
            <router-link to="/diary" class="more-link">更多 →</router-link>
          </div>
          <div v-if="latestDiary" class="showcase-content">
            <div class="diary-preview">
              <div class="diary-mood">{{ getMoodEmoji(latestDiary.mood) }}</div>
              <h4 class="diary-title">{{ latestDiary.title }}</h4>
              <p class="diary-excerpt">{{ getExcerpt(latestDiary.content) }}</p>
              <span class="diary-time">{{ formatDate(latestDiary.createdAt) }}</span>
            </div>
          </div>
          <div v-else class="showcase-empty">
            <p>还没有日记哦</p>
            <el-button size="small" @click="goToPage('/diary/create')">写第一篇</el-button>
          </div>
        </div>

        <!-- 未读小纸条 -->
        <div class="showcase-card card">
          <div class="showcase-header">
            <h3>💌 小纸条</h3>
            <router-link to="/notes" class="more-link">更多 →</router-link>
          </div>
          <div class="showcase-content">
            <div v-if="unreadNoteCount > 0" class="note-alert">
              <div class="alert-icon">✉️</div>
              <p class="alert-text">你有 <strong>{{ unreadNoteCount }}</strong> 条未读小纸条</p>
              <el-button type="primary" size="small" @click="goToPage('/notes')">
                查看
              </el-button>
            </div>
            <div v-else class="showcase-empty">
              <p>暂无新纸条</p>
              <el-button size="small" @click="goToPage('/notes')">发送纸条</el-button>
            </div>
          </div>
        </div>

        <!-- 即将到来的纪念日 -->
        <div class="showcase-card card">
          <div class="showcase-header">
            <h3>🎉 纪念日</h3>
            <router-link to="/anniversary" class="more-link">更多 →</router-link>
          </div>
          <div v-if="upcomingAnniversary" class="showcase-content">
            <div class="anniversary-preview">
              <div class="anniversary-icon">{{ getAnniversaryIcon(upcomingAnniversary.title) }}</div>
              <h4 class="anniversary-title">{{ upcomingAnniversary.title }}</h4>
              <p class="anniversary-date">{{ formatDate(upcomingAnniversary.date) }}</p>
              <p class="anniversary-countdown">{{ getCountdown(upcomingAnniversary.date, upcomingAnniversary.isAnnual) }}</p>
            </div>
          </div>
          <div v-else class="showcase-empty">
            <p>暂无即将到来的纪念日</p>
            <el-button size="small" @click="goToPage('/anniversary')">添加纪念日</el-button>
          </div>
        </div>

        <!-- 成就进度 -->
        <div class="showcase-card card">
          <div class="showcase-header">
            <h3>🏆 成就</h3>
            <router-link to="/achievement" class="more-link">更多 →</router-link>
          </div>
          <div class="showcase-content">
            <div class="achievement-stats">
              <div class="stats-circle">
                <div class="circle-progress">
                  <span class="progress-value">{{ achievedCount }}</span>
                  <span class="progress-total">/ {{ totalAchievements }}</span>
                </div>
              </div>
              <p class="stats-text">已解锁成就</p>
              <el-button size="small" @click="goToPage('/achievement')">查看全部</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 最近账单 -->
    <div class="recent-bills">
      <div class="section-header">
        <h2>📊 最近账单</h2>
        <router-link to="/bill/list" class="more-link">查看更多 →</router-link>
      </div>

      <div v-loading="loadingBills" v-if="recentBills.length > 0" class="bill-list">
        <div v-for="bill in recentBills" :key="bill.id" class="bill-item card">
          <div class="bill-icon">{{ getCategoryIcon(bill.category) }}</div>
          <div class="bill-info">
            <div class="bill-purpose">{{ bill.purpose }}</div>
            <div class="bill-meta">
              <span class="bill-category">{{ bill.category }}</span>
              <span class="bill-date">{{ formatDate(bill.billDate) }}</span>
            </div>
          </div>
          <div class="bill-amount" :class="{ 'my-bill': bill.isMine }">
            ¥ {{ formatAmount(bill.amount) }}
          </div>
        </div>
      </div>

      <div v-else class="empty-state">
        <div class="empty-state-icon">📝</div>
        <div class="empty-state-text">还没有账单记录哦</div>
        <el-button type="primary" @click="goToPage('/bill/create')" round>立即记账</el-button>
      </div>
    </div>

    <!-- 更换头像对话框 -->
    <el-dialog
      v-model="avatarDialogVisible"
      title="更换头像"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="avatar-upload-container">
        <!-- 未选择图片时显示 -->
        <div v-if="!selectedImageUrl" class="current-avatar">
          <el-avatar :size="120" :src="userInfo?.avatar || defaultAvatar">
            <el-icon><User /></el-icon>
          </el-avatar>
          <p class="avatar-tip">点击下方按钮选择新头像</p>

          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleAvatarChange"
            accept="image/*"
          >
            <el-button type="primary" :icon="Camera">选择图片</el-button>
          </el-upload>
        </div>

        <!-- 选择图片后显示裁剪器 -->
        <div v-else class="cropper-container">
          <div class="cropper-wrapper">
            <cropper
              ref="cropperRef"
              :src="selectedImageUrl"
              :stencil-props="{
                aspectRatio: 1
              }"
              @change="updatePreview"
            />
          </div>

          <div class="cropper-controls">
            <div class="control-group">
              <span class="control-label">缩放：</span>
              <el-button-group>
                <el-button size="small" @click="zoomIn">
                  <el-icon><ZoomIn /></el-icon>
                </el-button>
                <el-button size="small" @click="zoomOut">
                  <el-icon><ZoomOut /></el-icon>
                </el-button>
              </el-button-group>
            </div>

            <div class="control-group">
              <span class="control-label">旋转：</span>
              <el-button-group>
                <el-button size="small" @click="rotateLeft">
                  <el-icon><RefreshLeft /></el-icon>
                </el-button>
                <el-button size="small" @click="rotateRight">
                  <el-icon><RefreshRight /></el-icon>
                </el-button>
              </el-button-group>
            </div>

            <el-button size="small" @click="resetCropper">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>

            <el-button size="small" @click="reSelectImage">
              <el-icon><Picture /></el-icon>
              重新选择
            </el-button>
          </div>

          <div class="preview-section">
            <p class="preview-title">预览效果</p>
            <div class="preview-avatars">
              <div class="preview-item">
                <div class="preview-box preview-large" :style="previewStyle"></div>
                <span>大</span>
              </div>
              <div class="preview-item">
                <div class="preview-box preview-medium" :style="previewStyle"></div>
                <span>中</span>
              </div>
              <div class="preview-item">
                <div class="preview-box preview-small" :style="previewStyle"></div>
                <span>小</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAvatarDialog">取消</el-button>
          <el-button
            v-if="selectedImageUrl"
            type="primary"
            :loading="uploadLoading"
            @click="handleUploadAvatar"
          >
            确认更换
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Wallet,
  Coin,
  CreditCard,
  List,
  Bell,
  User,
  Camera,
  ZoomIn,
  ZoomOut,
  RefreshLeft,
  RefreshRight,
  Refresh,
  Picture,
  View
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import websocketManager from '@/utils/websocket'
import { Cropper } from 'vue-advanced-cropper'
import 'vue-advanced-cropper/dist/style.css'
import {
  getCoupleInfo,
  getTreasuryInfo,
  getBillList,
  getPendingBills,
  getDiaryList,
  getUnreadLoveNoteCount,
  getUpcomingAnniversaries,
  getUserAchievements,
  uploadFile,
  updateUserInfo
} from '@/api'

const router = useRouter()
const userStore = useUserStore()

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 处理头像 URL 的辅助函数
const processAvatarUrl = (avatar) => {
  if (!avatar) return ''
  if (avatar.startsWith('http')) return avatar

  // 如果是相对路径，拼接完整 URL
  const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
  return baseURL + avatar
}

// 用户信息（处理头像 URL）
const userInfo = computed(() => {
  const info = userStore.userInfo
  if (!info) return null

  return {
    ...info,
    avatar: processAvatarUrl(info.avatar)
  }
})

// 对方信息
const partnerInfo = ref(null)

// 头像上传相关
const avatarDialogVisible = ref(false)
const selectedImageUrl = ref('')
const uploadLoading = ref(false)
const uploadRef = ref(null)
const cropperRef = ref(null)
const previewStyle = ref({})

// 打开头像更换对话框
const openAvatarDialog = () => {
  avatarDialogVisible.value = true
  selectedImageUrl.value = ''
  previewStyle.value = {}
}

// 关闭头像更换对话框
const closeAvatarDialog = () => {
  avatarDialogVisible.value = false
  selectedImageUrl.value = ''
  previewStyle.value = {}
  if (selectedImageUrl.value) {
    URL.revokeObjectURL(selectedImageUrl.value)
  }
}

// 处理头像选择
const handleAvatarChange = (file) => {
  console.log('选择的文件：', file)

  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return
  }

  // 验证文件大小（最大 5MB）
  const isLt5M = file.raw.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB！')
    return
  }

  // 释放之前的 URL
  if (selectedImageUrl.value) {
    URL.revokeObjectURL(selectedImageUrl.value)
  }

  // 创建预览 URL
  selectedImageUrl.value = URL.createObjectURL(file.raw)
}

// 重新选择图片
const reSelectImage = () => {
  if (selectedImageUrl.value) {
    URL.revokeObjectURL(selectedImageUrl.value)
  }
  selectedImageUrl.value = ''
  previewStyle.value = {}
}

// 裁剪器控制函数
const zoomIn = () => {
  cropperRef.value?.zoom(1.1)
}

const zoomOut = () => {
  cropperRef.value?.zoom(0.9)
}

const rotateLeft = () => {
  cropperRef.value?.rotate(-90)
}

const rotateRight = () => {
  cropperRef.value?.rotate(90)
}

const resetCropper = () => {
  cropperRef.value?.reset()
}

// 更新预览
const updatePreview = ({ canvas }) => {
  if (canvas) {
    previewStyle.value = {
      backgroundImage: `url(${canvas.toDataURL()})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center'
    }
  }
}

// 上传头像
const handleUploadAvatar = async () => {
  if (!cropperRef.value) {
    ElMessage.warning('请先选择图片')
    return
  }

  uploadLoading.value = true
  try {
    // 1. 获取裁剪后的图片
    const { canvas } = cropperRef.value.getResult()

    if (!canvas) {
      throw new Error('获取裁剪图片失败')
    }

    // 2. 将 canvas 转换为 Blob
    const blob = await new Promise((resolve) => {
      canvas.toBlob(resolve, 'image/jpeg', 0.9)
    })

    // 3. 创建 FormData 并上传
    const formData = new FormData()
    formData.append('file', blob, 'avatar.jpg')

    const uploadRes = await uploadFile(formData)
    if (uploadRes.code !== 200 || !uploadRes.data) {
      throw new Error('上传失败')
    }

    console.log('头像上传成功，相对路径：', uploadRes.data)

    // 4. 更新用户信息
    const updateRes = await updateUserInfo({
      avatar: uploadRes.data  // 只保存相对路径
    })

    if (updateRes.code === 200) {
      // 5. 更新 store 中的用户信息
      userStore.setUserInfo(updateRes.data)

      ElMessage.success('头像更换成功 ✨')
      closeAvatarDialog()
    }
  } catch (error) {
    console.error('头像上传失败：', error)
    ElMessage.error(error.response?.data?.msg || '头像上传失败，请稍后重试')
  } finally {
    uploadLoading.value = false
  }
}

// 爱的留言（随机显示）
const loveMessages = [
  '💕 每一天都想和你在一起',
  '💖 有你的日子都是晴天',
  '✨ 你是我最美的意外',
  '💑 余生请多指教',
  '🌹 遇见你是最美的开始',
  '💝 爱你，是我做过最好的事',
  '🎀 你是我的小确幸',
  '💗 陪你到世界尽头'
]
const loveMessage = ref('')

// 分类图标映射
const categoryIcons = {
  '餐饮': '🍔',
  '购物': '🛍️',
  '交通': '🚗',
  '娱乐': '🎮',
  '医疗': '💊',
  '教育': '📚',
  '住房': '🏠',
  '其他': '📦'
}

// 恋爱天数
const loveDays = ref(0)

// 金库金额
const treasuryAmount = ref(0)

// 最近账单
const recentBills = ref([])

// 待审批账单数量
const pendingBillsCount = ref(0)

// 情侣关系信息
const coupleInfo = ref(null)

// 加载状态
const loadingBills = ref(false)

// 情感互动数据
const latestDiary = ref(null)
const unreadNoteCount = ref(0)
const upcomingAnniversary = ref(null)
const achievedCount = ref(0)
const totalAchievements = ref(0)

// 加载情侣关系信息
const loadCoupleInfo = async () => {
  try {
    const res = await getCoupleInfo()
    coupleInfo.value = res.data
    loveDays.value = res.data.daysTogether || 0

    // 获取对方信息并处理头像 URL
    const currentUserId = userStore.userInfo?.id
    if (res.data.user1?.id === currentUserId) {
      partnerInfo.value = {
        ...res.data.user2,
        avatar: processAvatarUrl(res.data.user2?.avatar)
      }
    } else {
      partnerInfo.value = {
        ...res.data.user1,
        avatar: processAvatarUrl(res.data.user1?.avatar)
      }
    }

    // 随机选择一条爱的留言
    const randomIndex = Math.floor(Math.random() * loveMessages.length)
    loveMessage.value = loveMessages[randomIndex]

    // 保存到 store
    userStore.setCoupleInfo(res.data)
  } catch (error) {
    console.error('获取情侣关系信息失败：', error)
    // 不显示错误提示，因为响应拦截器已经处理了
    // 页面会自动显示"还没有情侣关系"的引导界面
  }
}

// 加载金库信息
const loadTreasuryInfo = async () => {
  try {
    const res = await getTreasuryInfo()
    if (res.code === 200) {
      treasuryAmount.value = res.data.totalAmount || 0
    }
  } catch (error) {
    console.error('获取金库信息失败：', error)
  }
}

// 加载最近账单
const loadRecentBills = async () => {
  loadingBills.value = true
  try {
    const res = await getBillList({ pageNum: 1, pageSize: 5 })
    if (res.code === 200) {
      const currentUserId = userStore.userInfo?.id
      recentBills.value = res.data.records.map(bill => ({
        ...bill,
        isMine: bill.userId === currentUserId
      }))
    }
  } catch (error) {
    console.error('获取最近账单失败：', error)
  } finally {
    loadingBills.value = false
  }
}

// 加载待审批账单数量
const loadPendingBillsCount = async () => {
  try {
    const res = await getPendingBills()
    if (res.code === 200) {
      pendingBillsCount.value = res.data.length
    }
  } catch (error) {
    console.error('获取待审批账单数量失败：', error)
  }
}

// 获取分类图标
const getCategoryIcon = (category) => {
  return categoryIcons[category] || '📦'
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00'
  return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)

  if (d.toDateString() === today.toDateString()) {
    return '今天'
  } else if (d.toDateString() === yesterday.toDateString()) {
    return '昨天'
  } else {
    const month = d.getMonth() + 1
    const day = d.getDate()
    return `${month}月${day}日`
  }
}

// 跳转页面
const goToPage = (path) => {
  console.log('跳转到页面：', path)
  try {
    router.push(path)
    console.log('路由跳转成功')
  } catch (error) {
    console.error('路由跳转失败：', error)
    ElMessage.error('页面跳转失败，请稍后重试')
  }
}

// 查看对方的账单列表
const viewPartnerBills = () => {
  if (!partnerInfo.value || !partnerInfo.value.id) {
    ElMessage.warning('暂无对方信息')
    return
  }

  router.push({
    path: '/bill/list',
    query: {
      targetUserId: partnerInfo.value.id,
      targetUserName: partnerInfo.value.nickname || 'TA'
    }
  })
}

// 加载最新日记
const loadLatestDiary = async () => {
  try {
    const res = await getDiaryList({ pageNum: 1, pageSize: 1 })
    if (res.code === 200 && res.data.records && res.data.records.length > 0) {
      latestDiary.value = res.data.records[0]
    }
  } catch (error) {
    console.error('加载最新日记失败：', error)
  }
}

// 加载未读小纸条数量
const loadUnreadNoteCount = async () => {
  try {
    const res = await getUnreadLoveNoteCount()
    if (res.code === 200) {
      unreadNoteCount.value = res.data || 0
    }
  } catch (error) {
    console.error('加载未读小纸条数量失败：', error)
  }
}

// 加载即将到来的纪念日
const loadUpcomingAnniversary = async () => {
  try {
    const res = await getUpcomingAnniversaries()
    if (res.code === 200 && res.data && res.data.length > 0) {
      upcomingAnniversary.value = res.data[0]
    }
  } catch (error) {
    console.error('加载即将到来的纪念日失败：', error)
  }
}

// 加载成就数据
const loadAchievements = async () => {
  try {
    const res = await getUserAchievements()
    if (res.code === 200) {
      const achievements = res.data || []
      totalAchievements.value = achievements.length
      achievedCount.value = achievements.filter(item => item.achieved).length
    }
  } catch (error) {
    console.error('加载成就数据失败：', error)
  }
}

// 获取心情 emoji
const getMoodEmoji = (mood) => {
  const moodMap = {
    'happy': '😊',
    'sad': '😢',
    'excited': '😆',
    'calm': '😌',
    'angry': '😠',
    'love': '😍'
  }
  return moodMap[mood] || '😊'
}

// 获取摘要
const getExcerpt = (content) => {
  if (!content) return ''
  return content.length > 50 ? content.substring(0, 50) + '...' : content
}

// 获取纪念日图标
const getAnniversaryIcon = (title) => {
  if (title.includes('生日')) return '🎂'
  if (title.includes('恋爱') || title.includes('纪念')) return '💕'
  if (title.includes('见面')) return '👫'
  if (title.includes('领证') || title.includes('结婚')) return '💍'
  return '🎉'
}

// 获取倒计时
const getCountdown = (dateStr, isAnnual) => {
  if (!dateStr) return ''

  const today = new Date()
  today.setHours(0, 0, 0, 0)

  let targetDate = new Date(dateStr)

  // 如果是每年重复，计算今年的日期
  if (isAnnual) {
    targetDate = new Date(today.getFullYear(), targetDate.getMonth(), targetDate.getDate())

    // 如果今年的日期已过，则计算明年的日期
    if (targetDate < today) {
      targetDate.setFullYear(targetDate.getFullYear() + 1)
    }
  }

  const diffTime = targetDate - today
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) {
    return '🎉 就是今天！'
  } else if (diffDays > 0) {
    return `还有 ${diffDays} 天`
  } else {
    return '已过去'
  }
}

// 加载数据
const loadData = async () => {
  // 加载情侣关系信息
  await loadCoupleInfo()

  // 加载金库金额和最近账单
  loadTreasuryInfo()
  loadRecentBills()
  loadPendingBillsCount()

  // 加载情感互动数据
  loadLatestDiary()
  loadUnreadNoteCount()
  loadUpcomingAnniversary()
  loadAchievements()
}

// WebSocket 消息处理器
const handleWebSocketMessage = (notification) => {
  console.log('主页收到 WebSocket 消息', notification)

  // 根据消息类型刷新相应的数据
  switch (notification.type) {
    case 'NOTE_RECEIVED':
      // 刷新未读小纸条数量
      loadUnreadNoteCount()
      break
    case 'BILL_APPROVAL':
      // 刷新待审批账单数量
      loadPendingBillsCount()
      break
    case 'TREASURY_CHANGE':
      // 刷新金库信息
      loadTreasuryInfo()
      break
    case 'DIARY_COMMENT':
      // 刷新最新日记
      loadLatestDiary()
      break
    default:
      break
  }
}

onMounted(() => {
  loadData()

  // 添加 WebSocket 消息监听
  websocketManager.onMessage(handleWebSocketMessage)
})

onUnmounted(() => {
  // 移除 WebSocket 消息监听
  websocketManager.offMessage(handleWebSocketMessage)
})
</script>

<style scoped>
.home-container {
  max-width: 1200px;
  margin: 0 auto;
}

.love-countdown-card {
  margin-bottom: 30px;
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 50%, #ffd6e7 100%);
  color: #fff;
  text-align: center;
  padding: 50px 40px;
  position: relative;
  overflow: hidden;
}

.love-countdown-card::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
  animation: rotate 20s linear infinite;
  z-index: 0;
  pointer-events: none;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.countdown-content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  gap: 40px;
  position: relative;
  z-index: 1;
}

/* 头像相框 */
.avatar-frame {
  position: relative;
  flex-shrink: 0;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.avatar-frame:hover {
  transform: translateY(-5px);
}

.heart-frame {
  position: relative;
  width: 160px;
  height: 160px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.heart-svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  filter: drop-shadow(0 4px 12px rgba(255, 20, 147, 0.3));
}

.heart-path {
  animation: heartbeat 2s ease-in-out infinite;
}

@keyframes heartbeat {
  0%, 100% {
    transform: scale(1);
  }
  10%, 30% {
    transform: scale(1.05);
  }
  20%, 40% {
    transform: scale(1);
  }
}

.avatar-container {
  position: relative;
  z-index: 2;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

/* 头像悬浮提示 */
.avatar-hover-tip {
  position: absolute;
  bottom: -40px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255, 255, 255, 0.95);
  color: #ff69b4;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  white-space: nowrap;
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.3);
  opacity: 0;
  pointer-events: none;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.avatar-frame:hover .avatar-hover-tip {
  opacity: 1;
  bottom: -50px;
}

.couple-avatar {
  border: 4px solid rgba(255, 255, 255, 0.8);
  box-shadow: 0 8px 20px rgba(255, 20, 147, 0.4);
  background: linear-gradient(135deg, #fff 0%, #ffe0ec 100%);
}

.pulse {
  animation: pulse 3s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    box-shadow: 0 8px 20px rgba(255, 20, 147, 0.4);
  }
  50% {
    transform: scale(1.05);
    box-shadow: 0 12px 30px rgba(255, 20, 147, 0.6);
  }
}

.avatar-name {
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
  background: rgba(255, 255, 255, 0.2);
  padding: 5px 15px;
  border-radius: 20px;
  backdrop-filter: blur(10px);
}

/* 爱心粒子 */
.love-particles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.particle {
  position: absolute;
  font-size: 20px;
  animation: float 4s ease-in-out infinite;
  opacity: 0;
}

.particle:nth-child(1) {
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.particle:nth-child(2) {
  top: 60%;
  right: 10%;
  animation-delay: 1.5s;
}

.particle:nth-child(3) {
  bottom: 20%;
  left: 20%;
  animation-delay: 3s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) scale(0.8);
    opacity: 0;
  }
  50% {
    transform: translateY(-30px) scale(1.2);
    opacity: 1;
  }
}

/* 中间倒计时 */
.countdown-center {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.love-icon {
  font-size: 50px;
}

.floating {
  animation: floating 3s ease-in-out infinite;
}

@keyframes floating {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.countdown-text {
  text-align: center;
}

.countdown-text h2 {
  font-size: 24px;
  margin-bottom: 10px;
  font-weight: normal;
}

.countdown-days {
  font-size: 80px;
  font-weight: 900;
  line-height: 1;
  margin: 10px 0;
  color: #ffffff;
  /* 云朵风格的多层阴影 */
  text-shadow:
    0 2px 4px rgba(255, 255, 255, 0.8),
    0 4px 8px rgba(255, 192, 203, 0.6),
    0 6px 12px rgba(255, 182, 193, 0.5),
    0 8px 16px rgba(255, 105, 180, 0.4),
    0 10px 20px rgba(255, 105, 180, 0.3),
    0 12px 24px rgba(255, 105, 180, 0.2);
  filter: drop-shadow(0 0 20px rgba(255, 255, 255, 0.9));
  animation: cloudGlow 3s ease-in-out infinite;
  letter-spacing: 2px;
}

/* 云朵发光动画 */
@keyframes cloudGlow {
  0%, 100% {
    filter: drop-shadow(0 0 20px rgba(255, 255, 255, 0.9))
            drop-shadow(0 0 30px rgba(255, 192, 203, 0.6));
  }
  50% {
    filter: drop-shadow(0 0 30px rgba(255, 255, 255, 1))
            drop-shadow(0 0 40px rgba(255, 192, 203, 0.8))
            drop-shadow(0 0 50px rgba(255, 182, 193, 0.6));
  }
}

@keyframes glow {
  0%, 100% {
    filter: drop-shadow(0 0 10px rgba(255, 255, 255, 0.5));
  }
  50% {
    filter: drop-shadow(0 0 20px rgba(255, 255, 255, 0.8));
  }
}

.countdown-text p {
  font-size: 20px;
  font-weight: 500;
}

.love-message {
  font-size: 16px;
  font-style: italic;
  color: rgba(255, 255, 255, 0.95);
  background: rgba(255, 255, 255, 0.15);
  padding: 10px 25px;
  border-radius: 25px;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  animation: fadeIn 1s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.no-couple-content {
  text-align: center;
  padding: 20px;
  position: relative;
  z-index: 1;
}

.no-couple-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.no-couple-content h3 {
  font-size: 24px;
  margin-bottom: 10px;
  color: #fff;
}

.no-couple-content p {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 20px;
}

.couple-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  position: relative;
  z-index: 10;
}

.couple-actions .el-button {
  border-radius: 20px;
  cursor: pointer;
  pointer-events: auto;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.action-card {
  text-align: center;
  padding: 30px 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-card:hover {
  transform: translateY(-5px);
}

.action-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.action-card h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 8px;
}

.action-card p {
  font-size: 14px;
  color: #999;
}

.recent-bills {
  margin-top: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  font-size: 24px;
  color: #333;
}

.more-link {
  color: #ff9a9e;
  text-decoration: none;
  font-size: 14px;
  transition: all 0.3s;
}

.more-link:hover {
  color: #ff8a8e;
}

.bill-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.bill-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  transition: all 0.3s ease;
}

.bill-item:hover {
  background: #ffeef8;
  transform: translateX(5px);
}

.bill-icon {
  font-size: 32px;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  border-radius: 12px;
}

.bill-info {
  flex: 1;
}

.bill-purpose {
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
  font-weight: 500;
}

.bill-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

.bill-category {
  padding: 2px 8px;
  background: #f0f0f0;
  border-radius: 4px;
}

.bill-date {
  font-size: 12px;
  color: #999;
}

.bill-amount {
  font-size: 18px;
  font-weight: bold;
  color: #ff9a9e;
}

.bill-amount.my-bill {
  color: #67c23a;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-state-icon {
  font-size: 60px;
  margin-bottom: 16px;
}

.empty-state-text {
  font-size: 14px;
  color: #999;
  margin-bottom: 20px;
}

/* 情感互动展示区 */
.emotion-showcase {
  margin: 40px 0;
}

.showcase-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.showcase-card {
  padding: 20px;
}

.showcase-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #ffe5f1;
}

.showcase-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.showcase-content {
  min-height: 120px;
}

.showcase-empty {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

.showcase-empty p {
  margin: 0 0 12px 0;
}

/* 日记预览 */
.diary-preview {
  text-align: center;
}

.diary-mood {
  font-size: 36px;
  margin-bottom: 12px;
}

.diary-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.diary-excerpt {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.diary-time {
  font-size: 12px;
  color: #999;
}

/* 小纸条提醒 */
.note-alert {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #fff5f7 0%, #ffe5f1 100%);
  border-radius: 8px;
}

.alert-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.alert-text {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #666;
}

.alert-text strong {
  color: #ff69b4;
  font-size: 20px;
}

/* 纪念日预览 */
.anniversary-preview {
  text-align: center;
}

.anniversary-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.anniversary-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.anniversary-date {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.anniversary-countdown {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #ff69b4;
}

/* 成就统计 */
.achievement-stats {
  text-align: center;
  padding: 20px;
}

.stats-circle {
  width: 100px;
  height: 100px;
  margin: 0 auto 16px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(255, 215, 0, 0.3);
}

.circle-progress {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.progress-value {
  font-size: 32px;
  font-weight: bold;
  color: #fff;
  line-height: 1;
}

.progress-total {
  font-size: 14px;
  color: #fff;
  opacity: 0.9;
}

.stats-text {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #666;
}

/* 移动端适配 (< 768px) */
@media (max-width: 768px) {
  .home-container {
    padding: 0;
  }

  .page-title {
    font-size: 20px;
    margin-bottom: 16px;
    padding: 0 12px;
  }

  .love-countdown-card {
    padding: 24px 16px;
    border-radius: 12px;
    margin: 0 0 12px 0;
  }

  .countdown-content {
    flex-direction: row; /* 保持左右布局 */
    gap: 16px;
    justify-content: space-around; /* 改为 space-around，避免紧贴边缘 */
    align-items: center;
    padding: 0 8px; /* 添加左右内边距 */
  }

  .heart-frame {
    width: 90px;
    height: 90px;
  }

  .couple-avatar {
    width: 60px !important;
    height: 60px !important;
  }

  .avatar-name {
    font-size: 12px;
  }

  /* 移动端头像容器优化 */
  .avatar-frame {
    flex: 0 0 auto;
  }

  /* 移动端中间爱心和天数区域 */
  .countdown-center {
    flex: 0 0 auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
  }

  .avatar-hover-tip {
    font-size: 12px;
    padding: 6px 12px;
  }

  .love-icon {
    font-size: 32px;
  }

  .countdown-text h2 {
    font-size: 14px;
    margin-bottom: 4px;
  }

  .countdown-days {
    font-size: 36px;
    margin: 4px 0;
  }

  .countdown-text p {
    font-size: 12px;
    margin-top: 4px;
  }

  .love-message {
    font-size: 12px;
    padding: 6px 12px;
    margin-top: 8px;
  }

  .quick-actions {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    margin: 0 0 12px 0;
  }

  .action-card {
    padding: 16px 12px;
    border-radius: 10px;
  }

  .action-icon {
    font-size: 32px;
    margin-bottom: 6px;
  }

  .action-card h3 {
    font-size: 14px;
    margin-bottom: 4px;
  }

  .action-card p {
    font-size: 12px;
  }

  .showcase-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .showcase-card {
    padding: 16px;
    border-radius: 10px;
  }

  .showcase-card h3 {
    font-size: 15px;
    margin-bottom: 12px;
  }

  /* 移动端对话框优化 */
  .avatar-upload-container {
    padding: 12px 0;
    gap: 16px;
  }

  .cropper-wrapper {
    height: 300px;
  }

  .cropper-controls {
    flex-wrap: wrap;
    gap: 8px;
  }

  .control-group {
    flex: 1 1 auto;
  }

  .preview-section {
    padding: 12px;
  }

  .preview-avatars {
    gap: 12px;
  }

  .preview-large {
    width: 80px !important;
    height: 80px !important;
  }

  .preview-medium {
    width: 50px !important;
    height: 50px !important;
  }

  .preview-small {
    width: 35px !important;
    height: 35px !important;
  }
}

/* 小屏手机适配 (< 576px) */
@media (max-width: 576px) {
  .page-title {
    font-size: 18px;
  }

  .love-countdown-card {
    padding: 16px 10px;
  }

  .countdown-content {
    gap: 12px;
    justify-content: space-around; /* 确保小屏也使用 space-around */
    padding: 0 6px; /* 小屏减少内边距 */
  }

  .heart-frame {
    width: 75px;
    height: 75px;
  }

  .couple-avatar {
    width: 50px !important;
    height: 50px !important;
  }

  .avatar-name {
    font-size: 11px;
  }

  .love-icon {
    font-size: 28px;
  }

  .countdown-text h2 {
    font-size: 12px;
  }

  .countdown-days {
    font-size: 32px;
  }

  .countdown-text p {
    font-size: 11px;
  }

  .quick-actions {
    gap: 10px;
  }

  .action-card {
    padding: 14px 10px;
  }

  .action-icon {
    font-size: 28px;
  }

  .action-card h3 {
    font-size: 13px;
  }

  .action-card p {
    font-size: 11px;
  }

  .cropper-wrapper {
    height: 250px;
  }
}

/* 平板适配 (768px - 992px) */
@media (min-width: 768px) and (max-width: 992px) {
  .quick-actions {
    grid-template-columns: repeat(3, 1fr);
  }

  .showcase-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 横屏适配 */
@media (orientation: landscape) and (max-height: 500px) {
  .love-countdown-card {
    padding: 16px;
  }

  .countdown-content {
    flex-direction: row;
    gap: 20px;
  }

  .heart-frame {
    width: 80px;
    height: 80px;
  }

  .couple-avatar {
    width: 50px !important;
    height: 50px !important;
  }

  .countdown-days {
    font-size: 32px;
  }
}

/* 头像上传对话框样式 */
.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
  padding: 20px 0;
}

.current-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.avatar-tip {
  color: #999;
  font-size: 14px;
  margin: 0;
}

/* 裁剪器容器 */
.cropper-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.cropper-wrapper {
  width: 100%;
  height: 400px;
  background: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #e0e0e0;
}

.cropper-wrapper :deep(.vue-advanced-cropper) {
  height: 100%;
}

.cropper-wrapper :deep(.vue-advanced-cropper__background),
.cropper-wrapper :deep(.vue-advanced-cropper__foreground) {
  background: #f5f5f5;
}

/* 裁剪器控制按钮 */
.cropper-controls {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  flex-wrap: wrap;
  padding: 12px;
  background: #f9f9f9;
  border-radius: 8px;
}

.control-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.control-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

/* 预览区域 */
.preview-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: linear-gradient(135deg, #ffeef8 0%, #fff5f7 100%);
  border-radius: 12px;
}

.preview-title {
  color: #ff69b4;
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.preview-avatars {
  display: flex;
  gap: 24px;
  align-items: flex-end;
}

.preview-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.preview-item span {
  font-size: 12px;
  color: #999;
}

.preview-box {
  border-radius: 50%;
  border: 3px solid #fff;
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.3);
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.preview-large {
  width: 100px;
  height: 100px;
}

.preview-medium {
  width: 60px;
  height: 60px;
}

.preview-small {
  width: 40px;
  height: 40px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>

